<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="学院名称" prop="collegeName">
        <el-input
          v-model="queryParams.collegeName"
          placeholder="请输入学院名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="组卷名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入组卷名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:collegepaper:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:collegepaper:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:collegepaper:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:paper:export']"
        >导出</el-button>
      </el-col> -->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标识" align="center" prop="id" />
      <el-table-column label="学院名称" align="center" prop="collegeName" />
      <el-table-column label="组卷名称" align="center" prop="name" />
      <el-table-column label="总分" align="center" prop="score" />
      <el-table-column label="合格分" align="center" prop="standardScore" />
      <el-table-column label="题数" align="center" prop="questionCount" />
      <el-table-column label="同步时间" align="center" prop="syncDt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.syncDt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" align="center" prop="endDt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参考人数" align="center" prop="testerCount" />
      <el-table-column label="合格人数" align="center" prop="passerCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:collegepaper:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:collegepaper:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学院试卷对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <template>
          <el-radio-group v-model="radio" @change="selectZx">
            <el-radio :label="1">学校自主组卷</el-radio>
            <el-radio :label="2">抽取系统组卷</el-radio>
          </el-radio-group>
        </template>
        <br>
        <br>
        <el-form-item v-if="radio==2" label="系统组卷" prop="paperId">
           <el-select v-model="form.paperId"  placeholder="请选择系统组卷">
            <el-option
              v-for="item in xtpaperList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-button @click="selectPaperInfo" type="primary" style="margin-left: 16px;">点我打开</el-button>
        </el-form-item> 
        <el-form-item v-if="radio==1" label="组卷名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入组卷名称" />
        </el-form-item>
     <!--    <el-form-item v-if="radio==1" label="总分" prop="score">
          <el-input v-model="form.score" placeholder="请输入总分" />
        </el-form-item> -->
        <el-form-item v-if="radio==1" label="合格分" prop="standardScore">
          <el-input v-model="form.standardScore" placeholder="请输入合格分" />
        </el-form-item>
       <!--  <el-form-item  label="同步时间" prop="syncDt">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.syncDt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择同步时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="截止时间" prop="endDt">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.endDt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择截止时间">
          </el-date-picker>
        </el-form-item>

        <el-form :model="queryQuestionStoreParams" ref="queryQuestionStoreForm" :inline="true" v-if="radio==1" >
          <el-form-item  label="题型" prop="typeCode">
           <el-select v-model="queryQuestionStoreParams.typeCode"  placeholder="请选择题型">
            <el-option
              v-for="item in txOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> 
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryQuestionStore">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQueryQuestionStore">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row v-if="radio==1">
            <el-table v-loading="loading1" ref="list"  :data="questionStoreList" height="600px">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="标识" v-if="false" align="center" prop="id" />
              <el-table-column prop="typeName" label="题型"></el-table-column>
              <el-table-column  prop="content" label="题面">
                <template slot-scope="scope">
                  <span v-html="scope.row.content"></span>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="计分" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.score" ></el-input>
              </template>
            </el-table-column>
            </el-table>
            <pagination
              v-show="questionStoreTotal>0"
              :total="questionStoreTotal"
              :page-sizes="[30, 50, 100]"
              :page.sync="queryQuestionStoreParams.pageNum"
              :limit.sync="queryQuestionStoreParams.pageSize"
              @pagination="getQuestionStoreList"
            />
          </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <div>
      <el-drawer
        title="组卷详情"
        :visible.sync="drawer"
        :with-header="false"
        width="400">
      <el-form ref="form" :model="paperFrom"  label-width="100px">
        <div class="zjxq">主卷详情</div>

         <el-row>
           <el-col :span="12">
             <el-form-item label="名称" prop="name" >
                <el-input v-model="paperFrom.name" readonly />
              </el-form-item>
           </el-col>
             <el-col :span="12">
               <el-form-item label="总分" prop="score">
                <el-input v-model="paperFrom.score" readonly />
              </el-form-item>
           </el-col>
         </el-row>

          <el-row>
           <el-col :span="12">
              <el-form-item label="合格分" prop="standardScore">
                <el-input v-model="paperFrom.standardScore" readonly />
              </el-form-item>
           </el-col>
             <el-col :span="12">
              <el-form-item label="题数" prop="questionCount">
                <el-input v-model="paperFrom.questionCount" readonly />
              </el-form-item>
           </el-col>
         </el-row>

         <el-row>
             <el-col :span="12">
                <el-form-item label="有效时间天数" prop="validityDay">
                <el-input v-model="paperFrom.validityDay" readonly />
             </el-form-item>
           </el-col>
           <el-col :span="12">
              <el-form-item label="发布时间" prop="createDt">
                <el-date-picker readonly clearable size="small" style="width: 200px"
                  v-model="paperFrom.createDt"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择发布时间">
                </el-date-picker>
              </el-form-item>
           </el-col>
         </el-row>

          <el-row>
           <el-col :span="24">
               <el-form-item label="状态">
                  <el-radio-group  v-model="paperFrom.progressCode">
                    <el-radio disabled
                      v-for="dict in collegeStatusOptions"
                      :key="dict.dictValue" 
                      :label="parseInt(dict.dictValue)"
                      >{{ dict.dictLabel }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
           </el-col>
         </el-row>
         <el-row>
             <el-col :span="24">
                <el-form-item label="发布日期" prop="publishDt">
                <el-date-picker readonly clearable size="small" style="width: 200px"
                  v-model="paperFrom.publishDt"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择发布日期">
                </el-date-picker>
              </el-form-item>
           </el-col>
         </el-row>

        </el-form>
        <br>
        <el-form>
          <div class="zjxq">组卷题目：</div>
          <el-row>
            <el-table :data="paperQueList"  height="550" border style="width: 100%">
              <el-table-column prop="typeName" label="题型"></el-table-column>
              <el-table-column prop="content" label="题面">
               <template slot-scope="scope">
                  <span v-html="scope.row.content"></span>
                </template>
              </el-table-column>
               <el-table-column prop="score" label="计分"></el-table-column>
            </el-table>
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage4"
                :page-sizes="[30, 50, 100]"
                :page-size="pageSizeTable"
                layout="total, sizes, prev, pager, next, jumper"
                :total="paperQueList.length">
              </el-pagination>
          </el-row>
      </el-form>
      </el-drawer>  
    </div>
  </div>
  



</template>

<script>
import { getParerQueList,getPaperList,listquestionStore,listCollegePaper, getCollegePaper, delCollegePaper, addCollegePaper, updateCollegePaper, exportCollegePaper } from "@/api/system/collegePaper";

export default {
  name: "collegePaper",
  data() {
    return {
      pageSizeTable:10,
      //系统试卷表
      xtpaperList:[],
      //组卷方式
      radio:1,
          // 总条数
      questionStoreTotal: 0,
        //习题表格数据
      questionStoreList: [],

      //主卷表中的数据
      paperQueList:[],
       //记录组卷已有习题
      haveList: [],
      // 遮罩层
      loading: true,
       // 遮罩层
      loading1: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学院试卷表格数据
      paperList: [],
           // 状态字典
      collegeStatusOptions: [],
      // 删除位字典
      collegeIsDeleteOptions: [],
       //编辑习题类型
      txOptions: [{id:1,label:"判断题"},{id:2,label:"单选题"},{id:3,label:"多选题"}],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        collegeId: null,
        collegeName: null,
        paperId: null,
        name: null,
        score: null,
        standardScore: null,
        questionCount: null,
        syncDt: null,
        endDt: null,
        testerCount: null,
        passerCount: null
      },
      // 表单参数
      form: {},
      paperFrom:{},
      drawer: false,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        score: [
          { required: true, message: "总分不能为空", trigger: "blur" },
        ],
        standardScore: [
          { required: true, message: "合格分不能为空", trigger: "blur" },
        ],
      },
      queryQuestionStoreParams:{
        pageNum: 1,
        pageSize: 30,
        paperId: undefined,
        typeCode:undefined
      },
       currentPage4: 1
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_sj_state").then((response) => {
      this.collegeStatusOptions = response.data;
    });
  },
  methods: {
      handleSizeChange(val) {
        this.pageSizeTable = val;
      },
      handleCurrentChange(val) {
        this.currentPage4=val
      },

    collegeStatusFormat(row, column) {
      return this.selectDictLabel(this.collegeStatusOptions, row.progressCode);
    },
    //查看组卷详情
    selectPaperInfo(){
      console.log(this.form.paperId);
      if(this.form.paperId == undefined || this.form.paperId == '' || this.form.paperId == null){
         this.msgSuccess("请先选择组卷");
        return;
      }
       
      getParerQueList(this.form.paperId).then(response => {
        this.paperFrom = response.data;
        if(response.data.list.length == 0){
          this.msgSuccess("未配置习题");
        }else{
          this.paperQueList = response.data.list;
          this.drawer = true
        }
        
      });
    },
    //获取组卷方式
    selectZx(val){
       if(val==2){
          getPaperList().then(response =>{
              this.xtpaperList = response.rows;
          })
       }else{
         this.questionStoreList = this.haveList;
            this.$nextTick(()=>{
              this.$refs.list.toggleAllSelection();
            })
            this.handleQueryQuestionStore();
       }
    },
     //查询组卷
     getListPaper() {
       listPaper(this.queryParams).then(response => {
        this.paperOptions = response.rows;
      });
    },
      /** 查询学院试卷列表 */
    getList() {
      this.loading = true;
      listCollegePaper(this.queryParams).then(response => {
        this.paperList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
      //习题重置
     resetQueryQuestionStore(){
      this.resetForm("queryQuestionStoreForm");
      this.handleQueryQuestionStore();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        collegeId: null,
        collegeName: null,
        paperId: null,
        name: null,
        score: null,
        standardScore: null,
        questionCount: null,
        syncDt: null,
        endDt: null,
        testerCount: null,
        passerCount: null
      };
      this.resetForm("form");
      this.questionStoreList = [];
      this.radio = 1;
      this.questionStoreTotal = 0;
      this.queryQuestionStoreParams.typeCode = undefined; 
      this.xtpaperList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.handleQueryQuestionStore();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学院试卷";
      this.handleQueryQuestionStore();
    },

     //搜索习题
    handleQueryQuestionStore(){
       this.queryQuestionStoreParams.pageNum = 1;
       this.getQuestionStoreList();
    },
    getQuestionStoreList() {
      this.loading1 = true;
      listquestionStore(this.queryQuestionStoreParams).then(response => {
        this.questionStoreList = response.rows;
        this.questionStoreTotal = response.total;
        this.loading1 = false;
        const list = [];
          this.haveList = [];
          var resp = this.$refs.list.selection;
          resp.forEach(item => {
               if(item.score == undefined || item.score == '') this.$set(item, 'score', '0');
            this.haveList.push(item);
          });
          // questionStoreList是数组较长的那一组，haveList是较短的那组数组,haveList是记录组卷已有的习题，如果组卷需要查找新的习题，需要将已有的习题回写进去
          for(var i=0;i<this.haveList.length;i++){
              for(var j=0;j< this.questionStoreList.length;j++){ 
                  if( this.questionStoreList[j].id == this.haveList[i].id){
                    this.questionStoreList.splice(j,1);
                    j = j - 1;
                }
              }
          }
          this.haveList.forEach(item =>{
            this.questionStoreList.push(item);
          })
          this.$nextTick(()=>{
	            this.questionStoreList.forEach(row => {
              if(row.score != undefined && row.score !== ''){
              this.$refs.list.toggleRowSelection(row,true);
              }
	            });
          })
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.loading1 = true;
      getCollegePaper(id).then(response => {
       if(response.data.paperId==0){
          this.radio=1;
       }else{
            this.radio = 2;
             getPaperList().then(response =>{
              this.xtpaperList = response.rows;
          })
       }
        const resp = response.data;
        this.form = response.data;
        this.open = true;
        this.title = "修改学院试卷";
        this.getlistquestionStore(resp);
        
      });
    },
    getlistquestionStore(resp){
        listquestionStore(this.queryQuestionStoreParams).then(response1 => {
          this.loading1 = false;
          const data = response1.rows;
          resp.list.forEach(item => {
            data.forEach(item1 => {
              if(item.questionStoreId == item1.id){
                item1.score = item.score;
                this.questionStoreList.push(item1);
                return false;
              }
            });
          })
            this.questionStoreTotal = resp.list.length;
            this.haveList = this.questionStoreList;
            this.$nextTick(()=>{
              this.$refs.list.toggleAllSelection();
            })
          });
          
    },
  
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
      if(this.radio==1){
        if (valid) {
            var resp = this.$refs.list.selection;
             var listMap = [];
             var scoreCount = 0;
            resp.forEach(item => {
              var list = {};
              list.questionStoreId = item.id;
             list.score = item.score == undefined ? this.$set(item, 'score', '0') : item.score;
              scoreCount += parseInt(item.score);
              listMap.push(list);
            });
            this.form.list = listMap;    
            this.form.score = scoreCount;
            this.form.questionCount = this.form.list.length;
          if (this.form.id != null) {
            updateCollegePaper(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addCollegePaper(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      }else if(this.radio==2){

        if (valid) {
          if (this.form.id != null) {
            updateCollegePaper(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addCollegePaper(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }


      }

      });
    },



    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除学院试卷编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCollegePaper(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有学院试卷数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportCollegePaper(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>

<style scoped>
.zjxq{
  height: 33px;
  text-align: center;
  margin-top: 10px;
}
</style>
